from django.test import TestCase, Client
from django.urls import reverse
from django.contrib.auth.models import User
from .models import BlogUser

class UserRegisterTestCase(TestCase):

    def setUp(self):
        self.client = Client()

    def test_user_register_success(self):
        # 测试正常注册情况
        data = {
            'username': 'testuser',
            'password': 'password123',
            'phone': '1234567890'
        }
        response = self.client.post(reverse('user_register'), data, content_type='application/json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.json(), {'message': 'User registered successfully', 'code': 1})
        self.assertTrue(BlogUser.objects.filter(username='testuser').exists())

    def test_user_register_missing_data(self):
        # 测试缺少必要数据情况
        data = {
            'username': 'testuser2',
            'password': '',  # 缺少密码
            'phone': '1234567890'
        }
        response = self.client.post(reverse('user_register'), data, content_type='application/json')
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(), {'error': 'Username and password are required'})
        self.assertFalse(BlogUser.objects.filter(username='testuser2').exists())

    def test_user_register_exception(self):
        # 测试异常情况
        data = {
            'username': 'testuser3',
            'password': 'password123',
            'phone': '1234567890'
        }
        # 模拟异常发生
        with self.assertRaises(Exception):
            response = self.client.post(reverse('user_register'), data, content_type='application/json')
